package com.weixin.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weixin.pojo.WXUser;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class WXUserUtil {

    public static Map<String ,WXUser>  users = new HashMap<String, WXUser>();

    public static Map<String,List<WXUser>> DEPT_USERS = new HashMap<>();

    public static String getUserInfo(String accessToken,String code)throws Exception{
        String url = WxepConstants.getuserinfo_url.replace("{accessToken}",accessToken).replace("{code}",code);
        JSONObject jsonObject = WXUtil.httpRequest(url,"GET",null);
        log.info("getUserInfo url is {}, jsonObject is {}",url,jsonObject);
        if(WxepConstants.SUCCESS_CODE ==jsonObject.getInt("errcode")){
            return String.valueOf(jsonObject.get("UserId"));
//            wxUser.setDeviceId(jsonObject.getString("DeviceId"));
//            wxUser.setUserTicket(jsonObject.getString("user_ticket"));
        }
        return "";
    }

    public static WXUser getUser(String accessToken,String userId)throws Exception{
        if(users.get(userId) !=null){
            return users.get(userId);
        }
        if(StringUtils.isEmpty(accessToken)){
            accessToken = WXUtil.getToken(WxepConstants.CorpId,WxepConstants.REPAIRE_SECRET);
        }
        String url = WxepConstants.GET_USER_BYID_URL.replace("{accessToken}",accessToken).replace("{userId}",userId);
        JSONObject jsonObject = WXUtil.httpRequest(url,"GET",null);
        if(WxepConstants.SUCCESS_CODE ==jsonObject.getInt("errcode")){
            WXUser wxUser = assemblyUser(jsonObject);
            users.put(userId,wxUser);
            return wxUser;
        }
        return null;
    }
    
    public static WXUser assemblyUser(JSONObject jsonObject){
        WXUser wxUser = new WXUser();
        wxUser.setName(jsonObject.getString("name"));
        wxUser.setMobile(jsonObject.getString("mobile"));
        wxUser.setGender(jsonObject.getString("gender"));
        wxUser.setAvatar(jsonObject.getString("avatar"));
        wxUser.setDepartment(jsonObject.getString("department"));
        wxUser.setEmail(jsonObject.getString("email"));
        wxUser.setPosition(jsonObject.getString("position"));
        wxUser.setQr_code(jsonObject.getString("qr_code"));
        wxUser.setTelephone(jsonObject.getString("telephone"));
        wxUser.setUserid(jsonObject.getString("userid"));
       /* if(null != jsonObject.getJSONObject("external_profile")){
            JSONObject externalProfile = jsonObject.getJSONObject("external_profile");
            wxUser.setCorpName(externalProfile.getString("external_corp_name"));
        }*/
        return wxUser;
    }

    public static void main(String[] args) {
        String json = "{\"errcode\":0,\"isleader\":0,\"gender\":\"1\",\"mobile\":\"15021422141\",\"errmsg\":\"ok\",\"is_leader_in_dept\":[],\"telephone\":\"\",\"avatar\":\"https://wx.qlogo.cn/mmhead/Q3auHgzwzM7UqQ1Uwk8A3g5LQBeSx6t5QOdoErXcMib5luCZeXicj2Hg/0\",\"hide_mobile\":0,\"userid\":\"XuTao\",\"enable\":1,\"name\":\"徐涛\",\"extattr\":{\"attrs\":[]},\"qr_code\":\"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=vcd75ea2e245eebeb7\",\"alias\":\"\",\"position\":\"\",\"department\":[],\"email\":\"\",\"status\":1,\"order\":[]}";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            WXUser wxUser1 = objectMapper.readValue(json, WXUser.class);
            System.out.println(wxUser1);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    // 将userID转化为openID
    public static String convertToOpenid(String userId){
        String accessToken = WXUtil.getToken(WxepConstants.CorpId,WxepConstants.REPAIRE_SECRET);
        String url = WxepConstants.GET_OPENID_URL.replace("{accessToken}",accessToken);
        JSONObject json = new JSONObject();
        json.put("userid",userId);
        JSONObject result = WXUtil.httpRequest(url, "POST", json.toString());
        if(WxepConstants.SUCCESS_CODE ==result.getInt("errcode")){
            return result.getString("openid");
        }
        return "";
    }

    public static String  findCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies !=null){
            for (Cookie cookie: cookies) {
                if(cookie.getName().equals("userId")){
                    return cookie.getValue();
                }
            }
        }
        return "";
    }


}
